﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using FluentNHibernate.Cfg;
using System.Reflection;

namespace Tanmia.Basis
{
    public class SessionFactory
    {
        private static ISessionFactory sessionFactory;

        public static ISession Session
        {
            get
            {
                if (sessionFactory == null)
                    sessionFactory = CreateSessionFactory();

                try
                {
                    return sessionFactory.GetCurrentSession();
                }
                catch
                {
                    return sessionFactory.OpenSession();
                }
            }
        }

        private static ISessionFactory CreateSessionFactory()
        {
            Configuration cfg = new Configuration();
            cfg.Configure("NHibernate.config");
            try
            {
                Assembly asm = Assembly.LoadFrom("Tanmia.NHibernate.dll");
                FluentConfiguration fluConfig = Fluently.Configure(cfg);
                fluConfig.Mappings(m => { m.FluentMappings.AddFromAssembly(asm); });
                fluConfig.BuildConfiguration();
                return fluConfig.BuildSessionFactory();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
